/*
*	视图
*	renderCountry:绘制国家级数据地图
*/
var View = {
	//先绘制省级区块，再绘制国境线，在国境线一层绑定数据
	renderCountry : function(callback){
		var province_num = 0 ;
		var i,j,k;
		var province_total = CountryModel.source.length;
		//console.log("province_total" + province_total);
		var bdary=new BMap.Boundary();
		function setProvinceView(callback){
			for(i=0;i<province_total;i++){
				(function(){
					var province_name = CountryModel.source[i][0];
					var province_data = CountryModel.source[i][1];
					bdary.get(province_name,function(rs){
						var count = rs.boundaries.length;
						Cache.province_ply[province_name] = [];
						for( j=0 ; j < count ; j++){
							var ply = new BMap.Polygon(rs.boundaries[j], {strokeWeight: 1, strokeColor:"#FFFFFF",fillColor:MapModel.getDBColor(province_data),enableMassClear:false});
							//添加 Cache.provinceply 缓存
							Cache.province_ply[province_name].push(ply);
							ply.setStrokeStyle("dashed");
							MAP.addOverlay(ply);
						}
						province_num++;
					});
				})(i);	//闭包传参
			}
			callback();
		};
		//绘制省级区块后，执行回调绘制国境线、绑定点击事件
		setProvinceView(function(){
			var c_inter = setInterval(function(){
				if ( province_num == province_total ){
					var geoc = new BMap.Geocoder();    
					var ply = new BMap.Polygon(COUNTRYBOUNDARY[0], {strokeWeight:2,strokeColor:"#FFFFFF",fillColor:"transparent",enableMassClear:false});
					Cache.country_ply = ply;
					MAP.addOverlay(ply);
					//绑定在country_ply上的省份点击事件
					ply.addEventListener("click", function (e) {
			            var latlng = e.point;
			            geoc.getLocation(latlng, function(rs){
							var province = rs.addressComponents.province;
							var _data = CountryModel.getProvinceData(province);
							if(_data){
								var str = "<p><span id='info-name'>"+province+"</span><span class='infoTag' onclick='javascript:Control.toProvince();'>查看详情</span></p>"+"<p class='infoIndex'>噪声指数：<span>"+_data+"</span></p>";
								var info = new BMap.InfoWindow( str, {width:220});
				            	MAP.openInfoWindow(info, latlng);
			            	}
			            	MapModel.province = province;
			            	CardView.init();
						});
			        });
					clearInterval(c_inter);
				}
			},200);
		});
	},
	//绘制省级区域 zoom=7 显示所有省内城市区域图  显示城市级联菜单
	renderProvince : function(province_name,flag){
		var i,j,k;
		//获取市级区域信息并绘色  绘制省级边界线
		//缓存中读出边界信息  清空背景色
		Control.getData(2,function(){
			var i,j,k;
			var data = ProvinceModel.source;
			var city_total = ProvinceModel.source.length;
			var city_num = 0;
			var bdary=new BMap.Boundary();
		    //更新MapModel.city
			if (!flag) {
                //取消zoom:9跳回至zoom:7的city修改
			    MapModel.city = ProvinceModel.source[0][0];
			}
			CardView.initCityList();
			//切换View焦点和zoom缩放级
			var myGeo = new BMap.Geocoder();
			myGeo.getPoint(province_name, function(point){
				MapModel.center = [point.lng,point.lat];
				MAP.centerAndZoom(new BMap.Point(point.lng,point.lat),MapModel.zoom);
			});
			//绘制省级边界
			bdary.get(province_name,function(rs){
				var count = rs.boundaries.length;
				for( j=0 ; j < count ; j++){
					var ply = new BMap.Polygon(rs.boundaries[j], {strokeWeight: 1, strokeColor:"#FFFFFF",fillColor:"transparent"});
					ply.setStrokeStyle("solid");
					MAP.addOverlay(ply);
				}
				//todo 绘制市级区域图
				for(i=0;i<city_total;i++){
					(function(){
						var city_name = ProvinceModel.source[i][0];
						var city_data = ProvinceModel.source[i][1];
						bdary.get(city_name,function(rs){
							Cache.city_ply[city_name] = [];
							var count = rs.boundaries.length;
							for( j=0 ; j < count ; j++){
								var ply = new BMap.Polygon(rs.boundaries[j], {strokeWeight: 1, strokeColor:"#FFFFFF",fillColor:MapModel.getDBColor(city_data)});
								ply.setStrokeStyle("dashed");
								MAP.addOverlay(ply);
								//绑定城市区域点击事件
								ply.addEventListener("click", function (e) {
						            var latlng = e.point;
									var _data = ProvinceModel.getCityData(city_name);
									if(_data){
										var str = "<p><span id='info-name'>"+city_name+"</span><span class='infoTag' onclick='javascript:Control.toCity();'>查看详情</span></p>"+"<p class='infoIndex'>噪声指数：<span>"+_data+"</span></p>";
										var info = new BMap.InfoWindow( str, {width:220});
						            	MAP.openInfoWindow(info, latlng);
					            	}
					            	MapModel.city = city_name;
					            	//市级数据改变-Card更新
					            	CardView.init(true);
						        });
								Cache.city_ply[city_name].push(ply);
							}
							city_num++;
						});
					})(i);
				}
			});

		});
	},
	//绘制市级区域 zoom=9 显示城市的海量点数据图
	renderCity : function(city_name){
		var i,j,k;
		var myGeo = new BMap.Geocoder();
		var bdary=new BMap.Boundary();
		//从Cache.city_ply中获取缓存，加快渲染速度
		if( Cache.city_ply[city_name] ){
			//切换View焦点和zoom缩放级
			myGeo.getPoint(city_name, function(point){
				MapModel.center = [point.lng,point.lat];
				MAP.centerAndZoom(new BMap.Point(point.lng,point.lat),MapModel.zoom);
			});
			//绘制市区边框 & 打入海量点
			bdary.get(city_name,function(rs){
				var count = rs.boundaries.length;
				for( j=0 ; j < count ; j++){
					var ply = new BMap.Polygon(rs.boundaries[j], {strokeWeight: 1, strokeColor:"#FFFFFF",fillColor:"transparent"});
					ply.setStrokeStyle("dashed");
					MAP.addOverlay(ply);
				}
				//打点数据
				Control.getData(3,function(){
					var i,j,k;
					var length;
					var points= [];
					if (document.createElement('canvas').getContext) {
						length = CityModel.source.length;
						for(i=0;i<length;i++){
							points.push( new BMap.Point(CityModel.source[i][0],CityModel.source[i][1]) );
						}
				        for(i = 0;i<length;i++){
				        	(function(i){
					        	var pointCollection = new BMap.PointCollection([points[i]], {size: BMAP_POINT_SIZE_SMALLER,shape: BMAP_POINT_SHAPE_CIRCLE,color:MapModel.getDBColor(CityModel.source[i][2])});
						        MAP.addOverlay(pointCollection);
						    })(i);
				        }
				    }
				    else {
				        alert('请在chrome、safari、IE8+以上浏览器查看本网站。');
				        location.reload();
				    }
				});
			});
		}
	}
};





/*
*	噪声仪表板
*	init 初始化省级菜单栏和数字面板	
* 
*/
var CardView = {
	init : function(type){
		if(!type){
			//省级数据更新
			var data = CountryModel.source;
			var province_name = MapModel.province;
			var province_data = CountryModel.getProvinceData(MapModel.province) || "暂无数据";
			this.initProvinceList();
			this.initBoard(province_data);
			//省级数据显示时，隐藏城市数据菜单
			document.getElementById("city-box").style.display = "none";
		}
		else{
			//城市数据更新
			var data = ProvinceModel.source;
			var city_name = MapModel.city;
			var city_data = ProvinceModel.getCityData(MapModel.city) || "暂无数据";
			this.initCityList();
			this.initBoard(city_data);
		}	
	},
	//渲染数据色块面板
	initBoard : function(number){
		var obj = document.getElementById("dataCard");
		var str1 = '<span>'+number+'</span><small>db</small>';
		var str2 = "";
		if(number>=75){
			str2 = '<span class="card-item card-5" id="numberLevel">高度</span>';
		}
		else if( number<75 && number>= 72 ){
			str2 = '<span class="card-item card-4" id="numberLevel">中高</span>';
		}
		else if( number<72 && number>= 70 ){
			str2 = '<span class="card-item card-3" id="numberLevel">中度</span>';
		}
		else if( number<70 && number>= 65 ){
			str2 = '<span class="card-item card-2" id="numberLevel">中低</span>';
		}
		else if( number<65 && number>=0){
			str2 = '<span class="card-item card-1" id="numberLevel">低度</span>';
		}
		else{
			//暂无数据时无须显示程度色块
			str = "";
		}
		obj.innerHTML = str1+str2;
	},
	//渲染省级菜单
	initProvinceList : function(){
		var i = 0;
		var listArr = [];
		var str = "";
		var obj = document.getElementById("province-list");
		var tit = document.getElementById("province-title");
		for(var i = 0;i<CountryModel.source.length;i++){
			str = "<li>"+CountryModel.source[i][0]+"</li>";
			listArr.push(str);
		}
		obj.innerHTML = listArr.join('');
		tit.innerText = MapModel.province;
	},
	//渲染市级菜单
	initCityList : function(){
		var i = 0;
		var listArr = [];
		var str = "";
		var obj = document.getElementById("city-list");
		var tit = document.getElementById("city-title");
		for(var i = 0;i<ProvinceModel.source.length;i++){
			str = "<li>"+ProvinceModel.source[i][0]+"</li>";
			listArr.push(str);
		}
		obj.innerHTML = listArr.join('');
		tit.innerText = MapModel.city;
		document.getElementById("city-box").style.display = "block";
	},
	//显示下拉菜单
	showMenu : function(obj){
		if(obj.className=="select-icon"){
			obj.setAttribute("class", "select-icon-active"); 
			var list = obj.parentNode.querySelector('.select-list');
			list.style.display = "block";
		}
		else{
			obj.setAttribute("class", "select-icon"); 
			var list = obj.parentNode.querySelector('.select-list');
			list.style.display = "none";
		}
	},
	//选中下拉菜单
	clickMenu : function(type){
	    var myGeo = new BMap.Geocoder();
		if( type==1 ){
			//省级菜单选中
			var province_name = event.target.innerText;
			if( MapModel.zoom == 5 ){
				MapModel.province = province_name;
				CardView.init();
				myGeo.getPoint(province_name, function(point){
					var str = "<p><span id='info-name'>"+province_name+"</span><span class='infoTag' onclick='javascript:Control.toProvince();'>查看详情</span></p>"+"<p class='infoIndex'>噪声指数：<span>"+CountryModel.getProvinceData(province_name)+"</span></p>";
					var info = new BMap.InfoWindow( str, {width:220,'background-color':'red'});
		        	MAP.openInfoWindow(info,point);
				});
			}
			else{
				//zoom=7||9时，点击X省直接切回至全国视图
				MapModel.zoom = 5;
				MapModel.province = province_name;
				MAP.clearOverlays();
				//聚焦&调整缩放比
				myGeo.getPoint(province_name, function(point){
					MapModel.center = [point.lng,point.lat];
					MAP.centerAndZoom(new BMap.Point(point.lng,point.lat),MapModel.zoom);
					var str = "<p><span id='info-name'>"+province_name+"</span><span class='infoTag' onclick='javascript:Control.toProvince();'>查看详情</span></p>"+"<p class='infoIndex'>噪声指数：<span>"+CountryModel.getProvinceData(province_name)+"</span></p>";
					var info = new BMap.InfoWindow( str, {width:220,'background-color':'red'});
		        	MAP.openInfoWindow(info,point);
				});
				Cache.showCountryPly();
				Cache.showProvincePly();
				CardView.init();
				Control.loadNewData();
			}
			this.showMenu(document.getElementById("province-icon"));
		}
		else{
		    //城市菜单栏的点击事件
		    var city_name = event.target.innerText;
			if(MapModel.zoom==7){
				MapModel.city = city_name;
				CardView.init(true);
				myGeo.getPoint(city_name, function(point){
					var str = "<p><span id='info-name'>"+city_name+"</span><span class='infoTag' onclick='javascript:Control.toCity();'>查看详情</span></p>"+"<p class='infoIndex'>噪声指数：<span>"+ProvinceModel.getCityData(city_name)+"</span></p>";
					var info = new BMap.InfoWindow( str, {width:220});
		        	MAP.openInfoWindow(info,point);
				});
			}
			else if(MapModel.zoom==9){
				MapModel.zoom = 7;
				MapModel.city = city_name;
				CardView.init(true);
				MAP.clearOverlays();
				myGeo.getPoint(city_name, function(point){
					var str = "<p><span id='info-name'>"+city_name+"</span><span class='infoTag' onclick='javascript:Control.toCity();'>查看详情</span></p>"+"<p class='infoIndex'>噪声指数：<span>"+ProvinceModel.getCityData(city_name)+"</span></p>";
					var info = new BMap.InfoWindow( str, {width:220});
					MAP.openInfoWindow(info, point);
				});
				Control.loadNewData();
                //flag=true 取消省级视图渲染时的Model.city的二次修改
				View.renderProvince(MapModel.province,true);
			}
			else{
				//zoom=5 忽略事件（并隐藏city-box）
				document.getElementById("city-box").style.display = none;
			}
			this.showMenu(document.getElementById("city-icon"));
		}
	}
};





/*
*	时间轴
*	获取当前指示时间、更新MapModel中的date、滑动事件绑定
*/
var TimelineView = {
	//滑动相关控制参数&函数
	params : {
		left: 0,
		currentX: 0,
		flag: false
	},
	getCss : function(o,key){
		return o.currentStyle? o.currentStyle[key] : document.defaultView.getComputedStyle(o,false)[key]; 	
	},
	startDrag : function(bar, target, callback){
		bar = document.getElementById(bar);
		target = document.getElementById(target);
		if(this.getCss(target, "left") !== "auto"){
			this.params.left = this.getCss(target, "left");
		}
		//o是移动对象
		bar.onmousedown = function(event){
			TimelineView.params.flag = true;
			if(!event){
				event = window.event;
				//防止IE文字选中
				bar.onselectstart = function(){
					return false;
				}
			}
			var e = event;
			TimelineView.params.currentX = e.clientX;
		};
		document.onmouseup = function(){
			TimelineView.params.flag = false;	
			if( TimelineView.getCss(target, "left") !== "auto"){
				TimelineView.params.left = TimelineView.getCss(target, "left");
			}
			var nowLeft = parseInt(TimelineView.params.left);
			if( nowLeft%60 <= 30 ){
				nowLeft = nowLeft-nowLeft%60;
			}
			else{
				nowLeft = nowLeft+(60-nowLeft%60);
			}
			target.style.left = nowLeft + "px";
			TimelineView.params.left = nowLeft;
			//时间轴拖动后的新数据加载处理
			if( MapModel.date != TimelineView.getTime()){
				MapModel.date = TimelineView.getTime();
				Control.loadNewData();
			}
		};
		document.onmousemove = function(event){
			var e = event ? event: window.event;
			if(TimelineView.params.flag){
				var nowX = e.clientX;
				var disX = nowX - TimelineView.params.currentX;
				var resultX = disX + parseInt( TimelineView.params.left );
				if( resultX<=-1 || resultX>=540 ){
					return false;
				}
				target.style.left = resultX + "px";
			}
		}	
	},
	//时间操作函数
	initTime : function(){
		var li_arr = document.getElementById("timeline").querySelectorAll("li");
		var obj = li_arr[li_arr.length-1];
		var date = obj.getAttribute("date");
		//设置MapModel.date 
		MapModel.date = date;
	},
	getTime : function(){
		var o = this.params.left / 60 ;
		var li_arr = document.getElementById("timeline").querySelectorAll("li");
		var obj = li_arr[o];
		var date = obj.getAttribute("date");
		return date;
	}
};